package cn.huihuo.weibo.controller;

import cn.huihuo.weibo.bean.ProdCommentBean;
import cn.huihuo.weibo.bean.ProductResult;
import cn.huihuo.weibo.bean.PublishResultBean;
import cn.huihuo.weibo.module.*;
import cn.huihuo.weibo.service.FetchProductProcess;
import cn.huihuo.weibo.service.ParticipationService;
import cn.huihuo.weibo.utils.URLParam;
import cn.huihuo.weibo.utils.URLToParamUtil;
import cn.jfinalbbs.common.BaseController;
import cn.jfinalbbs.common.Constants;
import cn.jfinalbbs.user.User;
import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Dan
 *         Created by Administrator on 2015/8/27.
 */
public class ProductController extends BaseController {

    private static Map<String, String> map = new HashMap<>();


    public void index(){
        String prodId = getPara();
        Product product  = Product.product.findByProductId(prodId);
        if(product==null){ //如果不存在该商品直接跳转到首页
            redirect("/");
            return;
        }
        setAttr("product",product);

        User user = getSessionAttr(Constants.USER_SESSION);
        setAttr("participationSize", user==null?"": ParticipationService.service.findTotalParticipation(user.getStr("id")));

        List<ProductPic> prodPics = ProductPic.productPic.findByProductId(Integer.valueOf(prodId));
        setAttr("prodPics",prodPics);

        //查找讨论，等总条数
        ProdComment prodCommentSize = ProdComment.prodComment.prodTypeTotalSize(prodId, "2");
        setAttr("prodCommentSize",prodCommentSize);

        ProdComment extractSize = ProdComment.prodComment.prodTypeTotalSize(prodId, "3");
        setAttr("extractSize",extractSize);

        ProdComment channelSize = ProdComment.prodComment.prodTypeTotalSize(prodId, "4");
        setAttr("channelSize",channelSize);


        List<BuyChannel> buyChannels = BuyChannel.buyChannel.getBuyChannelByProdId(Integer.valueOf(prodId));
        for(BuyChannel buyChannel:buyChannels){
            if("bingfan".equals(buyChannel.get("channel_type"))){
                setAttr("bingfan",buyChannel);
            }
            if("hai360".equals(buyChannel.get("channel_type"))){
                setAttr("hai360",buyChannel);
            }
        }

        render("huihuo/product.html");
}

    @Before(Tx.class)
    public void beginFetch() {
        String url = getPara("url");

        FetchProductProcess process = getSessionAttr("process");
        ProductResult result = new ProductResult();
        if (process != null) {
            try {
                result = process.getProductResult();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            //获取出来正确的值
            if (!result.getStatus().equals("0")) {//如果已经完成或者不是正在进行的状态，则删除process的引用
                removeSessionAttr("process");
            }
        } else {

            FetchProductProcess fetchProductProcess = new FetchProductProcess(url, result);

            setSessionAttr("process", fetchProductProcess);
            new Thread(fetchProductProcess).start();
        }


        renderJson(result);
    }


    //发微博的时候需要校验登录
//    @Before(UserInterceptor.class)
    public void publishWeiBo() {
        try {
            String pic = getPara("picId");//获取商品ID
            String productId = getPara("productId");//获取商品ID

            User user = getSessionAttr(Constants.USER_SESSION);
            if (user == null) {
                error("用户名未登录");
                return;
            }
            ParticipationService.service.tryPutParticipation(user.getStr("id"),Integer.valueOf(productId));


            //先找到是否有改数据
            ProdComment pc = ProdComment.prodComment.findWeiBoByProdId(productId);

            PublishResultBean publishResultBean = new PublishResultBean();
            publishResultBean.setProductUrl("/product/"+productId);
            if (pc == null) {
                //保存发布的地方
                ProdComment prodComment = new ProdComment();

                prodComment.set("prod_id",productId).set("user_id",user.getStr("id")).set("ugc_type","1").save();
                publishResultBean.setStatus("1");
            } else {
                publishResultBean.setStatus("2");
            }
            success(publishResultBean);
        }catch (Exception e){
            e.printStackTrace();
            error("发布失败！");
        }

    }


    /**
     * 商品抓取
     */
//    public void fetchProduct(){
//        String url = getPara("url");
//        System.out.println(url);
//        //去后台调用
//        String skuId = getSkuId(url);
//        Product bySkuId = Product.product.findBySkuId(skuId);
//        ProductResult productResult = new ProductResult();
//        productResult.setPics(new ArrayList<>());
//        if(bySkuId!=null){//如果已经爬过
//            productResult.setProductName(bySkuId.get("prod_title"));
//            productResult.setProductId(String.valueOf(bySkuId.getInt("id")));
//            List<ProductPic> pics = ProductPic.productPic.findByProductId(String.valueOf(bySkuId.getInt("id")));
//            if(pics!=null){
//                for(ProductPic productPic:pics){
//                    Pic pic = new Pic();
//                    pic.setUrl(productPic.get("out_pic_path"));
//                    pic.setId(String.valueOf(productPic.getInt("id")));
//                    productResult.getPics().add(pic);
//                }
//            }
//            productResult.setStatus("OK");
//            renderJson(productResult);
//            return;
//        }
//
//        String productJson = getProductJson(url);
//        Gson gson = new Gson();
//        ExProduct exProduct = gson.fromJson(productJson, ExProduct.class);
//        System.out.println(productJson);
//        //要把该商品保存进数据库中
//
//
//        Product product = new Product();
//        product.set("prod_url",url)
//                .set("product_out_id",exProduct.getProductId()==null?skuId:exProduct.getProductId())
//                .set("prod_title",exProduct.getTitle())
//                .set("price",exProduct.getPrice())
//                .set("sku_id",skuId)
//                .set("price_current","USD").save();
//
//        String productId = String.valueOf(product.getInt("id"));
//        productResult.setProductId(productId);
//        productResult.setProductName(exProduct.getTitle());
//
//
//        for(String imgUrl:exProduct.getImageUrl()){
//            ProductPic productPic = new ProductPic();
//            productPic.set("prod_id",productId)
//                    .set("out_pic_path",imgUrl).save();
//            Integer picId = productPic.getInt("id");
//
//            Pic pic = new Pic();
//            pic.setUrl(imgUrl);
//            pic.setId(String.valueOf(picId));
//            productResult.getPics().add(pic);
//
//        }
//        productResult.setStatus("OK");
//
//
//        renderJson(productResult);
//
//    }

    /**
     * 发布微博
     */
    public void publish() {
        String prodId = getPara("prod_id");//获取商品ID
        String prodPic = getPara("prodPic");//获取选择的图片ID
        String text = getPara("text");//获取商品的ID
        User user = getSessionAttr(Constants.USER_SESSION);

        try {
            //保存进商品评论中
            ProdComment.prodComment.set("product_comment", text)
                    .set("prod_id", prodId)
                    .set("pic_id", prodPic)
                    .set("user_id", user.get("id")).save();

            success();
        } catch (Exception e) {
            error("");
        }
    }

    /**
     * 拉取微博
     */

//    public void findWeibo() {
//        String commentId = getPara("commentId");
//        //拉取微博以及用户
//        ProdComment prodComment = ProdComment.prodComment.findWeiBoById(commentId);
//
//
//        setAttr("prodComment", prodComment);
//        //拉取商品评论带分页,默认翻出第一页，定死10页
//
//        Page<Comment> commentPage = Comment.comment.findByProdCommentId(0, 10, commentId);
//
//        setAttr("commentPage", commentPage);
//
//        render("");//返回一个页面
//    }


    /**
     * 删除微博
     */
    public void deleteWeibo() {
        String commentId = getPara("commentId");
        boolean b = ProdComment.prodComment.deleteById(commentId);
        render("");
    }

    /**
     * 获取下拉分页
     */
    public void productComments() {
        int pageNumber = getParaToInt("page");
        Page<ProdComment> prodCommentPage = ProdComment.prodComment.findAllProductComment(pageNumber, 10);
        renderJson(prodCommentPage.getList());
    }


    public void test() {
        String commentId = getPara("commentId");
        ProdComment prodComment = ProdComment.prodComment.findWeiBoById(commentId);
        String prodId = prodComment.get("prod_id");//商品ID
        Product products = Product.product.findFirst("select * from product t where t.prod_id=?", prodId);


        String userId = prodComment.get("user_id");//用户ID
        User user = User.me.findFirst("select * from user t where t.id=? ", userId);
        String nickname = user.getStr("nickname");//用户名
        String userPic = user.getStr("avatar");//用户头像
        setAttr("userPic", userPic);
    }


    public String getProductJson(String url) {

        String str;
        try {
            HttpClient httpClient = new DefaultHttpClient();

            HttpGet get = new HttpGet(PropKit.use("config.properties").get("productRequest") + "?url=" + url);
            HttpResponse execute = httpClient.execute(get);

            str = EntityUtils.toString(execute.getEntity(), "utf-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return str;
    }


    public String getSkuId(String url) {
        String skuId = null;
        Pattern filter1 = Pattern.compile("[\\s\\S]*/dp/[\\s\\S]*");
        Pattern filter2 = Pattern.compile("[\\s\\S]*/gp/product/[\\s\\S]*");

        Matcher matcher1 = filter1.matcher(url);
        Matcher matcher2 = filter2.matcher(url);
        boolean match1 = matcher1.find();
        boolean match2 = matcher2.find();
        if (!(match1 || match2)) {
            throw new RuntimeException("url error!");
        }
        URL urlObj;
        try {
            urlObj = new URL(url);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        URLParam urlParam = URLToParamUtil.toParam(urlObj);
        List<String> pathParam = urlParam.getPathParam();
        if (match1) {
            int dp = pathParam.indexOf("dp");
            skuId = pathParam.get(dp + 1);

        }
        if (match2) {
            int gp = pathParam.indexOf("gp");
            skuId = pathParam.get(gp + 2);

        }
        return skuId;
    }
}
